<template>
  <div class="mt-checkbox-group">
    <van-checkbox-group
      value="{{ curValue }}"
      bind:change="onChange">
      <van-checkbox
        class="mt-checkbox-{{classes[index]}}"
        wx:for="{{options}}"
        wx:key="value"
        name="{{item.value}}">
        <block wx:if="{{!useSlot}}">{{item.label}}</block>
        <block wx:else><slot></slot></block>
      </van-checkbox>
    </van-checkbox-group>
  </div>
</template>

<script>
  const formEmitterBehavior = require('../../behaviors/emitter.behavior')
  const formELementBehavior = require('../../behaviors/form-element.behavior')

  export default {
    behaviors: [
      formEmitterBehavior,
      formELementBehavior
    ],
    relations: {
      '../mt-form-item/index': {
        type: 'ancestor', // 关联的目标节点应为祖先节点
        linked(v) {
          this.formItem = v
          // console.log('this.formItem', this.formItem)
        },
        unlinked() {
          this.formItem = null
        }
      }
    },
    properties: {
      sModel: null,
      items: {
        type: Array,
        value: [],
      },
      useSlot: {
        type: Boolean,
        value: false,
      }
    },

    computed: {
      options(data) {
        if (!data.items) {
          return []
        }
        return data.items
      },
      classes(data) {
        if (!data.curValue && data.curValue !== 0) {
          return data.items.map(v => {
            return 'uncheck'
          })
        }
        let ret = []
        data.items.forEach((v) => {
          if (data.curValue === v.value) {
            ret.push('checked')
          } else {
            ret.push('uncheck')
          }
        })
        console.log('checkboxgroup classes', ret)
        return ret
      },
    },
    data() {
      return {
        curValue: null,
        method: ''
      }
    },
    observers: {
      'sModel': function (field) {
        // console.log('field', field, this.data.sModel)
        this.setCurValue(this.data.sModel)
      }
    },
    attached: function () {
      this.formItem = null
    },
    methods: {
      onChange(e) {
        console.log('mtcheckbox onChange', e.detail)
        this.setCurValue(e.detail)
      },
      setCurValue(v) {
        // console.log('call setCurValue', v)
        let d = {
          curValue: v,
        }
        this.setData(d)
        this.callComponent(this.formItem, 'mtFormChange', [v])
      }
    },
  }
</script>

<style lang="scss">
</style>
